import { PageContainer } from '@ant-design/pro-layout';
import React, { useRef } from 'react';
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormSelect,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { Button, message } from 'antd';
import { useAccess, Access } from 'umi';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { request } from 'umi';
import { PlusOutlined, AlertOutlined, DeleteOutlined } from '@ant-design/icons';
import InsertOrUpdateComponent from './InsertOrUpdateComponent';
import { method } from 'lodash';
import { api } from '@/global';
type ProfessionType = {
  id: number;
  professionalName: string;
  professionalDesc: string;
  professionalCode: string;
  deptId: string;
  deptName: string;
  classesNumber: number;
  userNumber: number;

  professionalNumber: number;
};

export default () => {
  const actionRef = useRef<ActionType>();
  const access = useAccess();
  function reloadPage() {
    actionRef.current?.reload();
  }
  const columns: ProColumns<ProfessionType>[] = [
    {
      dataIndex: 'id',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '专业名称',
      dataIndex: 'professionalName',

      copyable: true,
    },
    {
      title: '专业代号',
      dataIndex: 'professionalCode',
    },

    {
      title: '专业描述',
      dataIndex: 'professionalDesc',
      search: false,
    },
    {
      title: '所属系部',
      dataIndex: 'deptName',
      valueType: 'select',

      initialValue: 0,
      request: async () => {
        const deptData = await request(api.getAllDept, {});
        const list: any[] = [];
        list.push({
          label: '全部',
          value: 0,
        });
        deptData.data.map((item: deptTyp) => {
          list.push({
            label: item.deptName,
            value: item.id,
          });
        });

        return list;
      },
    },
    {
      title: '该专业拥有的班级数量',
      dataIndex: 'classesNumber',
      filters: true,
      onFilter: true,
      sorter: (a, b) => a.classesNumber - b.classesNumber,
      search: false,
    },
    {
      title: '该专业现有用户数',
      dataIndex: 'userNumber',
      filters: true,
      onFilter: true,
      sorter: (a, b) => a.userNumber - b.userNumber,
      search: false,
    },

    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <Access
          key={'update' + record.id}
          accessible={access.normalButtonFilter('PROFESSIONAL:UPDATE')}
        >
          <ModalForm
            title="修改专业信息"
            key="id"
            autoFocusFirstInput
            modalProps={{
              destroyOnClose: true,
              onCancel: () => console.log('run'),
            }}
            onFinish={async (values) => {
              values.id = record?.id;
              const result = await request(
                api.insertProfessional,

                {
                  method: 'POST',
                  data: values,
                },
              );

              if (result.success) {
                message.info('添加成功');
                reloadPage();
                return true;
              } else {
                message.error('添加失败,请联系管理员');
                return false;
              }
            }}
            trigger={
              <Button title="新增系别" type="primary">
                <PlusOutlined />
                修改
              </Button>
            }
          >
            <ProForm.Group>
              <ProFormText
                width="sm"
                initialValue={record?.professionalName}
                name="professionalName"
                label="专业名称"
                rules={[
                  {
                    required: true,
                    message: '请输入专业名称',
                  },
                ]}
              />
              <ProFormText
                width="sm"
                initialValue={record?.professionalCode}
                name="professionalCode"
                label="专业编号"
                rules={[
                  {
                    required: true,
                    message: '请输入专业编号',
                  },
                ]}
              />
              <ProFormSelect
                width="sm"
                name="deptId"
                label="选择系部"
                rules={[
                  {
                    required: true,
                    message: '请选择系部',
                  },
                ]}
                initialValue={record?.deptId}
                request={async () => {
                  const deptData = await request(api.getAllDept, {});
                  const list: any[] = [];

                  deptData.data.map((item: deptTyp) => {
                    list.push({
                      label: item.deptName,
                      value: item.id,
                    });
                  });

                  return list;
                }}
              />
            </ProForm.Group>
            <ProFormTextArea
              initialValue={record?.professionalDesc}
              name="professionalDesc"
              label="专业描述"
              placeholder="请输入具体的专业描述"
            />
          </ModalForm>
        </Access>,
        <Access
          key={'delete' + record.id}
          accessible={access.normalButtonFilter('PROFESSIONAL:DELETE')}
        >
          <ModalForm
            key="id"
            title="删除专业"
            trigger={
              <Button type="danger">
                <DeleteOutlined />
                删除
              </Button>
            }
            submitter={{
              resetButtonProps: {
                type: 'dashed',
              },
            }}
            onFinish={async (values) => {
              const result = await request(
                api.deleteProfessional,

                {
                  method: 'DELETE',
                  data: {
                    id: record?.id,
                  },
                  skipErrorHandler: true,
                },
              ).catch((e) => {
                if (e.response.status === 500) {
                  message.error('该专业下面有用户或者课程存在');
                }
                return true;
              });

              if (result.success) {
                message.info('删除成功');
                actionRef.current?.reload();
                return true;
              } else {
                message.error('删除失败');
                return true;
              }
            }}
          >
            是否删除&nbsp;&nbsp;
            <span style={{ fontWeight: 900, fontSize: 25, color: '#3498db' }}>
              {record?.professionalName}
            </span>
            &nbsp;&nbsp; 专业
          </ModalForm>
        </Access>,
      ],
    },
  ];
  return (
    <PageContainer
      waterMarkProps={{ content: '山西工程技术学院' }}
      header={{
        title: '专业管理',
        breadcrumb: {
          routes: [
            {
              path: '',
              breadcrumbName: '组织管理',
            },
            {
              path: '',
              breadcrumbName: '专业管理',
            },
          ],
        },
      }}
    >
      <ProTable<ProfessionType>
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}, sort, filter) => {
          console.log(sort, filter);
          return request<{
            data: ProfessionType[];
          }>(api.getProfessionalList, {
            method: 'POST',
            data: {
              ...params,
            },
          });
        }}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        form={{
          // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
        headerTitle="专业信息"
        toolBarRender={() => [
          <Access
            key={'insertorupdate'}
            accessible={access.normalButtonFilter('PROFESSIONAL:INSERT')}
          >
            <InsertOrUpdateComponent reloadPage={reloadPage}></InsertOrUpdateComponent>
          </Access>,
        ]}
      />
    </PageContainer>
  );
};
